package com.xiaode.controller.app.secretProtection;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.SecretProtection;
import com.xiaode.common.model.UserAccount;
import com.xiaode.exce.EnumError;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class SecretProtectionService {
	/**
	 * 获取问题
	 * @param account
	 * @return
	 */
	public Ret getAnswer(String account) {
		SecretProtection sp = SecretProtection.dao.findFirst("SELECT * FROM secret_protection WHERE account = ? ", account);
		if(BeanUtil.isEmpty(sp)) {
			return Ret.fail().set("error", EnumError.SECRETPROTECTION_NOT_HAVE.getObj());
		}
		sp.remove("answer1","answer2","answer3");
		return Ret.ok("Answer", sp);
	}

	/**
	 * 校验密保
	 * @param account
	 * @param answer1
	 * @param answer2
	 * @param answer3
	 * @return
	 */
	public Ret getVerificationAnswer(String account, String answer1, String answer2, String answer3) {
		UserAccount ua = UserAccount.dao.findFirst("SELECT * FROM user_account WHERE account = ?", account);
		if(BeanUtil.isEmpty(ua)) {
			return Ret.fail().set("error", EnumError.ACCOUNT_NO.getObj());
		}
		SecretProtection sp = SecretProtection.dao.findFirst("SELECT * FROM secret_protection WHERE account = ? ", account);
		if(BeanUtil.isEmpty(sp)) {
			return Ret.fail().set("error", EnumError.SECRETPROTECTION_NOT_HAVE.getObj());
		}
		//验证次数
		if(sp.getFrequency() >= 3 && DateUtil.betweenDay(new Date(), Date.from(sp.getVerificationTime().atZone(ZoneId.systemDefault()).toInstant()), false) < 3) {
			return Ret.fail().set("error", EnumError.NOT_HAVE_FREQUENCY.getObj());
		}else if(sp.getFrequency() >= 3 && DateUtil.betweenDay(new Date(), Date.from(sp.getVerificationTime().atZone(ZoneId.systemDefault()).toInstant()), false) >= 3) {
			sp.setFrequency(1);
		}else {
			sp.setFrequency(sp.getFrequency() + 1);
		}
		sp.setVerificationTime(LocalDateTime.now());
		sp.update();
		if(StrUtil.equals(answer1, sp.getAnswer1()) && StrUtil.equals(answer2, sp.getAnswer2()) && StrUtil.equals(answer3, sp.getAnswer3())) {
			Cache redis = Redis.use();
			Long ac = System.currentTimeMillis();
			redis.setex(Const.SecretProtection.AnswerCode + account, 1800, ac);
			return Ret.ok("AnswerCode", ac);
		}
		return Ret.fail().set("error", EnumError.ANSWER_ERROR.getObj());
	}

	/**
	 * 通过密保修改密码
	 */
	public Ret setPasswordByProtection(String account, Long answerCode, String password) {
//		Admin admin = Admin.dao.findFirst("SELECT * FROM admin WHERE accountId = ?", accountId);
//		if(BeanUtil.isEmpty(admin)) {
//			return Ret.fail().set("error", EnumError.ACCOUNT_NO.getObj());
//		}
		Long ac = Redis.use().get(Const.SecretProtection.AnswerCode + account);
		if(ac == null) {
			return Ret.fail().set("error", EnumError.NEED_QUESTION_ANSWER.getObj());
		}
		if(!ac.equals(answerCode)) {
			return Ret.fail().set("error", EnumError.PARAMETER_ERROR.getObj());
		}
		Redis.use().del(Const.SecretProtection.AnswerCode + account);
		
		//修改
		UserAccount userAccount = UserAccount.dao.findFirst("SELECT * FROM user_account WHERE account = ?", account);
		password = SecureUtil.md5(password + userAccount.getId() + Const.salt);
		UserAccount ua = new UserAccount();
		ua.setId(userAccount.getId());
		ua.setPassword(password);
		ua.update();
		
        Redis.use().del(Const.user.loginStudent + userAccount.getId());
		return Ret.ok();
	}

	/**
	 * 添加密保
	 * @param admin
	 * @param problem1
	 * @param problem2
	 * @param problem3
	 * @param answer1
	 * @param answer2
	 * @param answer3
	 * @return
	 */
	@Before(Tx.class)
	public Ret addSecretProtection(String account, Integer userType, String problem1, String problem2, String problem3, String answer1, String answer2, String answer3) {
		//判断是否存在问题
		if(StrUtil.equals(problem1, problem2) || StrUtil.equals(problem3, problem2) || StrUtil.equals(problem1, problem3)) {
			return Ret.fail().set("error", EnumError.SECRETPROTECTION_PROBLEM_EQUALS.getObj());
		}
		//先删除再添加
		SecretProtection sp = SecretProtection.dao.findFirst("SELECT * FROM secret_protection WHERE account = ?", account);
		if(BeanUtil.isNotEmpty(sp)) {
			sp.delete();
		}
		//添加
		SecretProtection newsp = new SecretProtection();
		newsp.setProblem1(problem1);
		newsp.setProblem2(problem2);
		newsp.setProblem3(problem3);
		newsp.setFrequency(0);
		newsp.setAddTime(LocalDateTime.now());
		newsp.setUpdateTime(LocalDateTime.now());
		newsp.setAnswer1(answer1);
		newsp.setAnswer2(answer2);
		newsp.setAnswer3(answer3);
		newsp.setAccount(account);
		newsp.setUserType(userType);
		newsp.save();
		return Ret.ok("SecretProtection", newsp);
	}

	/**
	 * 是否设置密保
	 * @param admin
	 * @return
	 */
	public Ret isExistence(String account) {
		SecretProtection sp = SecretProtection.dao.findFirst("SELECT id FROM secret_protection WHERE account = ? ", account);
		return Ret.ok("isExistence", BeanUtil.isEmpty(sp) ? false : true);
	}

	/**
	 * 获取密保信息
	 * @param admin
	 * @return
	 */
	public Ret getSecretProtectionInfo(String account) {
		SecretProtection sp = SecretProtection.dao.findFirst("SELECT * FROM secret_protection WHERE account = ?", account);
		if(BeanUtil.isEmpty(sp)) {
			return Ret.fail().set("error", EnumError.SECRETPROTECTION_NOT_HAVE.getObj());
		}
		return Ret.ok("Answer", sp);
	}

	/**
	 * 获取密保问题
	 * @return
	 */
	public Ret getProblemInfo() {
		Cache redis = Redis.use();
		Map<String, String> problemInfoMap = new HashMap<String, String>();
		Set<String> problems = redis.keys(Const.SecretProtection.problem + "*");
		for(String problem : problems) {
			String name = redis.get(problem);
			problemInfoMap.put(problem.split(":")[1], name);
		}
		return Ret.ok("problemInfoMap", problemInfoMap);
	}

	

	

	
	
	
}

